package gui

import (
	"dyhttp/httputils"
	"image/color"
	"os"
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"github.com/flopp/go-findfont"
)

func init() {
	//设置中文字体:解决中文乱码问题
	fontPaths := findfont.List()
	for _, path := range fontPaths {
		if strings.Contains(path, "msyh.ttf") || strings.Contains(path, "simhei.ttf") || strings.Contains(path, "simsun.ttc") || strings.Contains(path, "simkai.ttf") {
			os.Setenv("FYNE_FONT", path)
			break
		}
	}
}

type Window struct {
	win fyne.Window
}

func NewWindow(title string, width, height float32) {
	a := app.New()
	//a.Settings().SetTheme(myTheme{})
	//a.Settings().Theme().Font(fyne.TextStyle{Bold: true, Symbol: true, TabWidth: 2})
	w := a.NewWindow(title)
	w.CenterOnScreen()
	win := new(Window)

	win.win = w

	win.SetContent()
	w.Resize(fyne.NewSize(width, height))
	w.ShowAndRun()
}

func (m *Window) SetContent() {
	m.win.SetContent(container.NewBorder(nil, nil, nil, nil, m.TabsContent()))
}

func (m *Window) TabsContent() fyne.CanvasObject {
	// http工具
	httpGui := httputils.NewHttpGui(m.win)

	tabs := container.NewAppTabs(
		container.NewTabItem("HTTP工具", httpGui),
		//container.NewTabItem("二维码工具", m.previewWidget),
	)
	tabs.SetTabLocation(container.TabLocationTop)
	return tabs
}

type myTheme struct{}

func (myTheme) Color(c fyne.ThemeColorName, v fyne.ThemeVariant) color.Color {
	return theme.DefaultTheme().Color(c, v)
}

func (myTheme) Font(s fyne.TextStyle) fyne.Resource {
	if s.Monospace {
		return theme.DefaultTheme().Font(s)
	}
	if s.Bold {
		if s.Italic {
			return theme.DefaultTheme().Font(s)
		}
		return theme.DefaultTheme().Font(s)
	}
	if s.Italic {
		return theme.DefaultTheme().Font(s)
	}
	return theme.DefaultTheme().Font(s)
}

func (myTheme) Icon(n fyne.ThemeIconName) fyne.Resource {
	return theme.DefaultTheme().Icon(n)
}

func (myTheme) Size(s fyne.ThemeSizeName) float32 {
	switch s {
	case theme.SizeNameText:
		return 15
	default:
		return theme.DefaultTheme().Size(s)
	}
}
